#include "mainw.h"
#include "ui_mainw.h"
#include <QtSql>
#include <QDebug>
#include <QString>
#include <QSqlTableModel>
#include <QSqlQueryModel>
#include <QMessageBox>
#include<QCheckBox>
#include<QHBoxLayout>
#include<QWidget>
#include<QFileDialog>
#include<QPainter>
#include "dialog.h"
#include"mydata.h"
#include<QEventLoop>
MainW::MainW(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::MainW)
{
    ui->setupUi(this);
    sdk =new  My_SDK();
    onlineThread=new OnlineThread();
    //QLineEdit
    listEdit.append(ui->lineEdit);
    listEdit.append(ui->lineEdit_2);
    listEdit.append(ui->lineEdit_3);
    listEdit.append(ui->lineEdit_4);
    listEdit.append(ui->lineEdit_5);
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("./my.db");
    if (!db.open())
    {
        qDebug()<<"open database failed ---"<<db.lastError().text()<<"/n";
    }
    QSqlQuery query(db);
    this->query=query;
     bool ok = query.exec("CREATE TABLE IF NOT EXISTS  EQUIPMENT (ID INTEGER PRIMARY KEY AUTOINCREMENT,BUILDING  VARCHAR(20) NOT NULL,UNIT  VARCHAR(20) NOT NULL,ROOM  VARCHAR(20) NOT NULL,ADMIN VARCHAR(20),IP  NOT NULL unique,ONLINE VARCHAR(5) default '未知')");
    if (ok)
    {
        qDebug()<<"ceate table partition success/n";
    }
    else
    {
        qDebug()<<"ceate table partition failed/n";
    }
    ui->tableWidget->setColumnCount(8);   //设置列数
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
    QStringList header;
    header <<"选择状"<<"楼号"<<"单元"<<"住户"<<"IP地址"<<"状态"<<"负责人"<<"ID";
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->setShowGrid(false);
    setStyle();

    ui->tableWidget_2->setColumnCount(6);   //设置列数
    ui->tableWidget_2->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableWidget_2->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_2->setSelectionMode(QAbstractItemView::ExtendedSelection);
    header.clear();
    header <<"楼号"<<"单元"<<"住户"<<"IP地址"<<"状态"<<"负责人";
    ui->tableWidget_2->setHorizontalHeaderLabels(header);
    ui->tableWidget_2->setShowGrid(false);
    setStyle2();

    timer= new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(autoUpdate()));
    timer->start(10000);
}
MainW::~MainW()
{
    delete ui;
}

void MainW::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
void MainW::paintEvent(QPaintEvent *)//背景
{
//   QPixmap pix("images/test.jpg");
//   QPainter painter(this);
//   int w = width();
//   int h = height();
//   painter.drawPixmap(0,0,w,h,pix);
    // QPixmap pix("images/test.jpg");
        QPainter painter(this);
    //151 255 255
        painter.setBrush(QColor(240,255,255));

        int w = width();
        int h = height();

        painter.drawRect(0,0,w,h);
      //  painter.drawPixmap(0,0,w,h,pix);
}
void MainW::reciveOnline(bool cse)
{
    this->cse=cse;
}
void MainW::autoUpdate()
{
    this->timer->stop();
    int rRow=ui->tableWidget->rowCount();
    for(int i=0;i<rRow;i++)
    {
        ip=ui->tableWidget->item(i,4)->text();
        autoId=ui->tableWidget->item(i,7)->text();
        str="update  EQUIPMENT  set ONLINE='";
        onlineThread->setIp(ip);
        onlineThread->start();
        QEventLoop eventLoop;
        connect(onlineThread,SIGNAL(finished()),&eventLoop,SLOT(quit()));
        connect(onlineThread,SIGNAL(sendOnline(bool )),this,SLOT(reciveOnline(bool)));
        eventLoop.exec();
        if(cse)
        {
            str+="在线' where ID=";
            str+=autoId;
            query.exec(str);
        }
        else
        {
            str+="离线' where ID=";
            str+=autoId;
            query.exec(str);
        }
    }
    setStyle();
    setStyle2();
    this->timer->start(10000);
}
void MainW::OutPutStyle(QString str1)///输出格式
{
   /* save+=ui->tableWidget->horizontalHeaderItem(1)->text();
    save+="：";
    save+=QString("%1").arg(build,-6);
    save+=" ";
    save+=ui->tableWidget->horizontalHeaderItem(2)->text();
    save+="：";
    save+=QString("%1").arg(unit,-6);
    save+=" ";
    save+=ui->tableWidget->horizontalHeaderItem(3)->text();
    save+="：";
    save+=QString("%1").arg(room,-6);
    save+=" ";
    save+=ui->tableWidget->horizontalHeaderItem(4)->text();
    save+="：";
    save+=QString("%1").arg(ip,-15);
    save+=" ";
    save+=str1;
    save+="  ";
    time=QDateTime::currentDateTime();
    save+=time.toString("hh:mm:ss");
    ui->textBrowser->append(save);
    save.clear();*/
}
void MainW::on_pushButton_clicked() //测试
{

    checkRow.clear();
    GetCheckState();
    int on=0,off=0;
    for(int i=0;i<checkRow.size();i++)
    { 
        int tmp=checkRow.at(i);
        build=ui->tableWidget->item(tmp,1)->text();
        unit=ui->tableWidget->item(tmp,2)->text();
        room=ui->tableWidget->item(tmp,3)->text();
        ip=ui->tableWidget->item(tmp,4)->text();
        id=ui->tableWidget->item(tmp,7)->text();
        str="update  EQUIPMENT  set ONLINE='";
        if(sdk->online(ip))
        {
            str+="在线' where ID=";
            str+=id;
            query.exec(str);
            on++; 
        }
        else
        {
            str+="离线' where ID=";
            str+=id;
            query.exec(str);
            off++;
            qDebug()<<str;
        }
    }
    setStyle();
    setStyle2();
    MyMessage(on,off,"在线","离线");
}



void MainW::on_pushButton_2_clicked()//插入 添加
{
    dialog=new Dialog(this);
    dialog->show();
    connect(dialog,SIGNAL(sendMassge(Mydata &)),this,SLOT(reciveMyData(Mydata &)));
}
void MainW::reciveMyData(Mydata &mydata)
{
    if(mydata.cse)
        update(mydata);
    else
        insert(mydata);

}
void MainW::insert(Mydata &mydata)
{
    //ui->textBrowser->clear();
     str.clear();
     str="insert into EQUIPMENT (BUILDING,UNIT,ROOM,ADMIN,IP) VALUES ( '";
     str+=mydata.build;
     str+="','";
     str+=mydata.unit;
     str+="','";
     str+=mydata.room;
     str+="','";
     str+=mydata.admin;
     str+="','";
     str+=mydata.ip;
     str+="')";
     bool ok=query.exec(str);
     if(query.lastError().number()==19)
     {
         QMessageBox::information(this, tr("提示"), "IP地址重复");
         return;
     }
     setStyle();
}
void MainW::update(Mydata &mydata)
{
    //ui->textBrowser->clear();
    int off=0;int on=0;
    bool ok;
    save="更新>>\n";
    str="update  EQUIPMENT  set BUILDING='";
    str+=mydata.build;
    str+="',IP='";
    str+=mydata.ip;
    str+="',UNIT='";
    str+=mydata.unit;
    str+="',ROOM='";
    str+=mydata.room;
    str+="',ADMIN='";
    str+=mydata.admin;
    str+="' where ID=";
    str+=upId;
    id=upId;
    qDebug()<<str;
    if((ok=query.exec(str)))
    {
        on++;

    }
    off=1-on;
    setStyle();
    MyMessage(on,off,"更新成功","更新失败");

}

void MainW::on_pushButton_3_clicked() //删除
{
    checkRow.clear();
    GetCheckState();
    int on=0,off=0;
    for(int i=0;i<checkRow.size();i++)
    {

        int tmp=checkRow.at(i);
        build=ui->tableWidget->item(tmp,1)->text();
        unit=ui->tableWidget->item(tmp,2)->text();
        room=ui->tableWidget->item(tmp,3)->text();
        ip=ui->tableWidget->item(tmp,4)->text();
        id=ui->tableWidget->item(tmp,7)->text();
        str="delete from EQUIPMENT where ID='";
        str+=id;
        str+="'";
        qDebug()<<str;
       if(query.exec(str))
        {
           on++;
        }
       else
       {
           off++;
       }
    }
    setStyle();
    MyMessage(on,off,"删除成功","删除失败");
}
void MainW::on_pushButton_4_clicked() //更行
{
    checkRow.clear();
    GetCheckState();
    if(checkRow.size())
    {
        int tmp=checkRow.at(0);
        build=ui->tableWidget->item(tmp,1)->text();
        unit=ui->tableWidget->item(tmp,2)->text();
        room=ui->tableWidget->item(tmp,3)->text();
        admin=ui->tableWidget->item(tmp,6)->text();
        upId=ui->tableWidget->item(tmp,7)->text();
        ip=ui->tableWidget->item(tmp,4)->text();
    }
    else
    {
        return ;
    }
    dialog=new Dialog(ip,build,unit,room,admin,this);
    dialog->show();
    connect(dialog,SIGNAL(sendMassge(Mydata &)),this,SLOT(reciveMyData(Mydata &)));
}
void MainW::setStyle()
{
    ui->tableWidget->setColumnWidth(0,80);
    ui->tableWidget->setColumnWidth(1,135);
    ui->tableWidget->setColumnWidth(2,155);
    ui->tableWidget->setColumnWidth(3,136);
    ui->tableWidget->setColumnWidth(4,160);
    ui->tableWidget->setColumnWidth(5,111);
    ui->tableWidget->setColumnWidth(6,112);
    int rRow=ui->tableWidget->rowCount();
    for(int i=0;i<rRow;i++)
    {
        ui->tableWidget->removeRow(0);
    }
    ui->checkBox->setCheckState(Qt::Unchecked);
    query.exec(QString("select BUILDING,UNIT,ROOM,IP,ONLINE,ADMIN,ID FROM  EQUIPMENT %1").arg(where));
    while(query.next())
    {
         int row=ui->tableWidget->rowCount();
         ui->tableWidget->insertRow(row);

         ui->tableWidget->verticalHeader()->hide();
         ui->tableWidget->setColumnHidden(7,true);

         ui->tableWidget->setCellWidget(row,0,new QCheckBox());

         ui->tableWidget->setItem(row,1,new QTableWidgetItem(query.value(0).toString()));
         ui->tableWidget->item(row,1)->setTextAlignment(Qt::AlignCenter);

         ui->tableWidget->setItem(row,2,new QTableWidgetItem(query.value(1).toString()));
         ui->tableWidget->item(row,2)->setTextAlignment(Qt::AlignCenter);

         ui->tableWidget->setItem(row,3,new QTableWidgetItem(query.value(2).toString()));
         ui->tableWidget->item(row,3)->setTextAlignment(Qt::AlignCenter);

         ui->tableWidget->setItem(row,4,new QTableWidgetItem(query.value(3).toString()));
         ui->tableWidget->item(row,4)->setTextAlignment(Qt::AlignCenter);

         ui->tableWidget->setItem(row,5,new QTableWidgetItem(query.value(4).toString()));
         ui->tableWidget->item(row,5)->setTextAlignment(Qt::AlignCenter);

         ui->tableWidget->setItem(row,6,new QTableWidgetItem(query.value(5).toString()));
         ui->tableWidget->item(row,6)->setTextAlignment(Qt::AlignCenter);

         ui->tableWidget->setItem(row,7,new QTableWidgetItem(query.value(6).toString()));
         ui->tableWidget->item(row,7)->setTextAlignment(Qt::AlignCenter);
    }
}
void MainW::setStyle2()
{
       ui->tableWidget_2->setColumnWidth(0,80);
       ui->tableWidget_2->setColumnWidth(1,125);
       ui->tableWidget_2->setColumnWidth(2,125);
       ui->tableWidget_2->setColumnWidth(3,165);
       ui->tableWidget_2->setColumnWidth(4,105);
       ui->tableWidget_2->setColumnWidth(5,110);
        int rRow=ui->tableWidget_2->rowCount();
        for(int i=0;i<rRow;i++)
        {
            ui->tableWidget_2->removeRow(0);
        }
        query.exec("select BUILDING,UNIT,ROOM,IP,ONLINE,ADMIN FROM  EQUIPMENT  WHERE  ONLINE='离线'");
        while(query.next())
        {
             int row=ui->tableWidget_2->rowCount();
             ui->tableWidget_2->insertRow(row);
             ui->tableWidget_2->verticalHeader()->hide();
             ui->tableWidget_2->setItem(row,0,new QTableWidgetItem(query.value(0).toString()));
             ui->tableWidget_2->item(row,0)->setTextAlignment(Qt::AlignCenter);

             ui->tableWidget_2->setItem(row,1,new QTableWidgetItem(query.value(1).toString()));
             ui->tableWidget_2->item(row,1)->setTextAlignment(Qt::AlignCenter);

             ui->tableWidget_2->setItem(row,2,new QTableWidgetItem(query.value(2).toString()));
             ui->tableWidget_2->item(row,2)->setTextAlignment(Qt::AlignCenter);

             ui->tableWidget_2->setItem(row,3,new QTableWidgetItem(query.value(3).toString()));
             ui->tableWidget_2->item(row,3)->setTextAlignment(Qt::AlignCenter);

             ui->tableWidget_2->setItem(row,4,new QTableWidgetItem(query.value(4).toString()));
             ui->tableWidget_2->item(row,4)->setTextAlignment(Qt::AlignCenter);

             ui->tableWidget_2->setItem(row,5,new QTableWidgetItem(query.value(5).toString()));
             ui->tableWidget_2->item(row,5)->setTextAlignment(Qt::AlignCenter);
        }
}

void  MainW::MyMessage(int &on,int &off,QString str1,QString str2) ///消息
{
    str.clear();
    str+=str1;
    str+=":";
    str+=QString::number(on);
    str+="\n";
    str+=str2;
    str+=":";
    str+=QString::number(off);
    QMessageBox::information(this, tr("提示"),str);
}
void MainW::on_tableWidget_clicked(QModelIndex  index) //获取单元格坐标
{
    ui->lineEdit->setText(index.sibling(index.row(),1).data().toString());
    ui->lineEdit_2->setText(index.sibling(index.row(),2).data().toString());
    ui->lineEdit_3->setText(index.sibling(index.row(),3).data().toString());
   ui->lineEdit_4->setText(index.sibling(index.row(),4).data().toString());
   ui->lineEdit_5->setText(index.sibling(index.row(),5).data().toString());
    QCheckBox  *pp=qobject_cast<QCheckBox  *>(ui->tableWidget->cellWidget(index.row(),0));
    if(pp->checkState()==Qt::Checked)
        pp->setCheckState(Qt::Unchecked);
    else
        pp->setCheckState(Qt::Checked);
    int rRow=ui->tableWidget->rowCount();
    int  selectedCount=0;
    for (int i = 0; i <rRow; i++)
    {
        if(((QCheckBox  *)(ui->tableWidget->cellWidget(i,0)))->checkState()==Qt::Checked)
            selectedCount++;
    }
     qDebug()<<selectedCount;
    if (selectedCount <= 0)
    {
          //未选中状态
       ui->checkBox->setCheckState(Qt::Unchecked);
    }
    else if (selectedCount > 0 && selectedCount < rRow)
    {
         //部分选中状态
        ui->checkBox->setCheckState(Qt::Unchecked);
    }
    else if (selectedCount ==rRow)
    {
         //选中状态
       ui->checkBox->setCheckState(Qt::Checked);
    }
}

void MainW::GetCheckState()
{
     int rRow=ui->tableWidget->rowCount();
     for(int i=0;i<rRow;i++)
     {
       QCheckBox  *pp=qobject_cast<QCheckBox *>(ui->tableWidget->cellWidget(i,0));
       if(pp->checkState()==Qt::Checked)
           checkRow.append(i);
     }
     qDebug()<<checkRow;
}
void MainW::on_pushButton_5_clicked()///另存为
{
     //ui->textBrowser->clear();
    QString fileName = QFileDialog::getSaveFileName (this,tr("保存"),"../",tr("File(*.csv)"));
    if(!fileName.isEmpty ())
    {
         QFile file(fileName);
         if(!file.open(QIODevice::WriteOnly))
         {
              QMessageBox msgBox;
              msgBox.setText("保存文件失败");
              msgBox.exec();
          }
          else
         {
               QString save;
               save=ui->tableWidget->horizontalHeaderItem(1)->text();
               save+=",";
               save+=ui->tableWidget->horizontalHeaderItem(2)->text();
               save+=",";
               save+=ui->tableWidget->horizontalHeaderItem(3)->text();
               save+=",";
               save+=ui->tableWidget->horizontalHeaderItem(4)->text();
               save+=",";
               save+=ui->tableWidget->horizontalHeaderItem(5)->text();
               save+=",";
               save+=ui->tableWidget->horizontalHeaderItem(6)->text();
               save+='\n';
               int rRow=ui->tableWidget->rowCount();
               for(int i=0;i<rRow;i++)
               {
                    save+=ui->tableWidget->item(i,1)->text();
                    save+=',';
                    save+=ui->tableWidget->item(i,2)->text();
                    save+=',';
                    save+=ui->tableWidget->item(i,3)->text();
                    save+=',';
                    save+=ui->tableWidget->item(i,4)->text();
                    save+=',';
                    save+=ui->tableWidget->item(i,5)->text();
                    save+=',';
                    save+=ui->tableWidget->item(i,6)->text();
                    save+='\n';
               }
               qDebug()<<save;
               QTextStream stream(&file);
               stream <<save;
               stream.flush ();
               file.close ();
         }
    }
}
void MainW::on_pushButton_6_clicked()//导入
{
     QString fileName = QFileDialog::getOpenFileName(this,tr("导入文件..."),"../",tr("File(*.csv)"));
     //QTextCodec *gbk = QTextCodec::codecForName("GB18030");
     int effectRow=0;
     if(!fileName.isEmpty ())
     {
         QFile file(fileName);
         if(!file.open(QIODevice::ReadOnly))
         {
              QMessageBox msgBox;
              msgBox.setText("导入文件失败");
              msgBox.exec();
          }
          else
          {
              QTextStream stream(&file);
              stream.setCodec(QTextCodec::codecForName("GB18030"));
              QString line;
              line=stream.readLine();
              line=stream.readLine();
              while(!line.isNull()&&!line.isEmpty())
              {
                /// QString g2u= gbk->toUnicode(gbk->fromUnicode(line));

                  qDebug()<<line;
                  QStringList list;
                     list=line.split(",");
                   str.clear();
                   str="insert into EQUIPMENT (BUILDING,UNIT,ROOM,IP,ADMIN) VALUES ( '";
                   str+=list.at(0);
                   str+="','";
                   str+=list.at(1);
                   str+="','";
                   str+=list.at(2);
                   str+="','";
                   str+=list.at(3);
                   str+="','";
                   str+=list.at(4);
                   str+="')";
                   line=stream.readLine();
                   qDebug()<<str;
                   if(query.exec(str))
                       effectRow++;
              }
              file.close();
          }
     }
     fileName=QString("导入%1条数据").arg(effectRow);
     QMessageBox::information(this, tr("提示"),fileName);
}
void MainW::on_checkBox_clicked(bool checked) //全选
{
    if(checked)
    {
        int rRow=ui->tableWidget->rowCount();
        for(int i=0;i<rRow;i++)
        {
           QCheckBox  *pp=qobject_cast<QCheckBox  *>(ui->tableWidget->cellWidget(i,0));
            pp->setCheckState(Qt::Checked);
        }
    }
    else
    {
        int rRow=ui->tableWidget->rowCount();
        for(int i=0;i<rRow;i++)
        {
            QCheckBox  *pp=qobject_cast<QCheckBox  *>(ui->tableWidget->cellWidget(i,0));
             pp->setCheckState(Qt::Unchecked);
        }
    }
}
void MainW::on_checkBox_clicked()
{

}
void MainW::on_pushButton_7_clicked()//查询
{
   QString key[]={"BUILDING","UNIT","ROOM","IP","ONLINE"};
   QString temp;
   int i=0;
   bool cse=true;
   where.clear();
   for(i=0;i<listEdit.size();i++)
   {
       if(!(temp=listEdit.at(i)->text()).isEmpty())
       {
           if(cse==true)
           {
                where+=" where ";
                cse=false;
           }
           else
                where+=" and ";
           where+=key[i];
           where+="='";
           where+=temp;
           where+="'";
       }
   } //where BUILDING='楼'and UNIT='二单元'and ROOM='12309'and IP='123.89.777.88'and ONLINE='离线'"
   setStyle();
   qDebug()<<where;
}

void MainW::on_tableWidget_activated(QModelIndex index)
{

}

